package Sort;

public class Sorts {

    // 直接插入排序
    public void InsertSort(int[] array) {
        for (int i = 1; i < array.length; i++) {
            int j = i - 1;
            int tmp = array[i];
            for (; j >= 0; j--) {
                if (array[j] > tmp) {
                    array[j + 1] = array[j];
                } else {
                    break;
                }
            }
            array[j + 1] = tmp;
        }
    }

    // 希尔排序
    public void ShellSort(int[] array) {
        int get = array.length;
        while (get > 1) {
            get /= 2;
            shell(array, get);
        }
    }

    public void shell(int[] array, int get) {
        for (int i = get; i < array.length; i++) {
            int j = i - get;
            int tmp = array[i];
            for (; j >= 0; j -= get) {
                if (array[j] > tmp) {
                    array[j + get] = array[j];
                } else {
                    break;
                }
            }
            array[j + get] = tmp;
        }
    }

    // 直接选择排序
    public void SelectSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int midIndex = i;
            int tmp = array[i];
            for (int j = i + 1; j < array.length; j++) {
                if (array[midIndex] > array[j]) {
                    midIndex = j;
                }
            }
            array[i] = array[midIndex];
            array[midIndex] = tmp;
        }
    }

    //冒泡排序
    public void bubblingSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int tmp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = tmp;
                }
            }
        }
    }

    // 堆排序
    public void heapSort(int[] array) {
        createHeap(array);
        int end=array.length-1;
        while (end>0){
            swap(array,0,end);
            siftDown(array,0,end);
            end--;
        }
    }

    public void createHeap(int[] array) {
        for (int parent = (array.length - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(array, parent, array.length);
        }
    }

    public void siftDown(int[] array, int parent, int len) {
        int child = (parent * 2) + 1;
        while (child < len) {
            if (child + 1 < len && array[child] < array[child + 1]) {
                child = child + 1;
            }
            if (array[child] > array[parent]) {
                swap(array,child,parent);
                parent=child;
                child=(parent*2)+1;
            }else {
                break;
            }
        }
    }

    public void swap(int[] array, int parent, int child) {
        int tmp = array[child];
        array[child] = array[parent];
        array[parent] = tmp;
    }

}
